package cz.data.domain.metadata.model;

import cz.data.common.core.DataConstant;
import cz.data.common.exception.DataException;
import cz.data.common.support.db.DbProperty;
import cz.data.common.support.db.core.DbColumn;
import cz.data.common.support.db.core.DbTable;
import cz.data.domain.metadata.model.dto.DbSchema;
import cz.data.domain.metadata.model.entity.MetadataColumnEntity;
import cz.data.domain.metadata.model.entity.MetadataSourceEntity;
import cz.data.domain.metadata.model.entity.MetadataTableEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class MetadataUtil {

    public static DbProperty dbProperty(MetadataSourceEntity source) {
        DbSchema schema = source.getDbSchema();
        return new DbProperty(source.getId(), source.getDbType(), schema.getHost(),
                schema.getUsername(), schema.getPassword(), schema.getPort(),
                schema.getDbName(), schema.getSid(), schema.getSchemaName(), schema.getMaxConn());
    }


    public static DbTable createDbTable(String tableId,
                                 Function<String, MetadataTableEntity> tableEntityFunction,
                                 Function<String, List<MetadataColumnEntity>> tableColumnFunction) {
        if (StringUtils.isBlank(tableId)) {
            throw new DataException("不存在表信息");
        }
        MetadataTableEntity table = tableEntityFunction.apply(tableId);
        List<MetadataColumnEntity> tableColumns = tableColumnFunction.apply(tableId);
        DbTable dbTable = new DbTable();
        dbTable.setTableName(table.getTableName());
        dbTable.setTableComment(table.getTableComment());
        List<DbColumn> columns = new ArrayList<>();
        for (MetadataColumnEntity tableColumn : tableColumns) {
            DbColumn column = new DbColumn();
            column.setColName(tableColumn.getColumnName());
            column.setColComment(tableColumn.getColumnComment());
            column.setDataType(tableColumn.getDataType());
            column.setColKey(DataConstant.TrueOrFalse.TRUE.equalsKey(tableColumn.getColumnKey()));
            column.setDataLength(tableColumn.getDataLength());
            if (StringUtils.isNotBlank(tableColumn.getColumnPosition())) {
                column.setColPosition(NumberUtils.toInt(tableColumn.getColumnPosition()));
            }
            column.setDataScale(tableColumn.getDataScale());
            column.setNullable(DataConstant.TrueOrFalse.FALSE.equalsKey(tableColumn.getColumnNullable()));
            column.setDataDefault(tableColumn.getDataDefault());
            columns.add(column);
        }
        dbTable.setColumns(columns);
        return dbTable;
    }
}
